package com.example.gc.webredisgc;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author sjw
 * @className TenantDataSourceManager
 * @date 2021/9/19 10:41
 * @description: TODO
 */
public class TenantDataSourceManager {
    private static final ThreadLocal<Integer> ctx = new ThreadLocal<>();
    private static final Map<Integer, DataSource> dataSourceMap = new HashMap<>();

    static {
        HikariConfig hikariConfig=new HikariConfig();
        hikariConfig.setJdbcUrl("jdbc:mysql://192.168.10.96:3306/app?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT");
        hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
        hikariConfig.setUsername("root");
        hikariConfig.setPassword("123456");
        dataSourceMap.put(1, new HikariDataSource(hikariConfig));
        HikariConfig hikariConfig1=new HikariConfig();
        hikariConfig1.setJdbcUrl("jdbc:mysql://192.168.10.96:3307/app?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT");
        hikariConfig1.setDriverClassName("com.mysql.cj.jdbc.Driver");
        hikariConfig1.setUsername("root");
        hikariConfig1.setPassword("123456");
        dataSourceMap.put(2, new HikariDataSource(hikariConfig1));
    }

    public static void setTenantId(Integer tenantId) {
        ctx.set(tenantId);
    }

    public static Integer getTenantId() {
        Integer tenantId = ctx.get();
        return tenantId;
    }

    public static void removeTenantId() {
        ctx.remove();
    }

    public static DataSource getDataSource() {
        Integer tenant = ctx.get();
        if (tenant == null) return null;
        return dataSourceMap.get(tenant);
    }
}
